﻿using AutoMapper;
using Mes.Application.Common.Resource;
using Mes.Application.Common;
using Mes.Application.DTO.Inputs.Quality;
using Mes.Application.DTO.Inputs.WorkOrders;
using Mes.Domain.BoundedContext.Entities.Quality;
using Mes.Infrastructure.Data.BoundedContext.Repositories.MasterData;
using Mes.Infrastructure.Data.BoundedContext.Repositories.Quality;
using Mes.Infrastructure.Data.BoundedContext.Repositories.WorkOrders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mes.Domain.BoundedContext.Entities.WorkOrders;
using Mes.Application.DTO.Results.WorkOrders;
using Mes.Application.DTO.Results.Quality;
using Mes.Domain.BoundedContext;
using System.Linq.Expressions;
using Mes.Infrastructure.Data.BoundedContext.Extensions;

namespace Mes.Application.Services.Quality
{
    public class SampleFreqService : ISampleFreqService
    {
        private readonly IMapper _mapper;
        private readonly ISampleFreqRepository _sampleFreqRepository;
        private readonly ISamplePlanFreqLinkRepository _samplePlanFreqLinkRepository;
        public SampleFreqService(IMapper mapper, ISampleFreqRepository sampleFreqRepository, ISamplePlanFreqLinkRepository samplePlanFreqLinkRepository)
        {
            if (mapper == null || sampleFreqRepository == null)
            {
                throw new ArgumentNullException();
            }
            _mapper = mapper;
            _sampleFreqRepository = sampleFreqRepository;
            _samplePlanFreqLinkRepository = samplePlanFreqLinkRepository;
        }

        /// <summary>
        /// 添加采样计划频率
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddSampleFreqAsync(AddingSampleFreqInput input)
        {
            //间隔时间不能小于10秒
            if (input.Interval_Unit == 0 && input.Interval < 10)
            {
                throw new CustomException(Messages.SampleFreqIntevalCannotLessThen10S);
            }
            //采样计划频率名称不能重复
            if (await _sampleFreqRepository.ExistsAsync(x => x.Freq_Name == input.Freq_Name))
            {
                throw new CustomException(Messages.SampleFreqNameMustBeUnique);
            }
            var freq = _mapper.Map<SampleFreq>(input);
            await _sampleFreqRepository.AddAsync(freq);
            int status = await _sampleFreqRepository.SaveAsync();
            if (status <= 0)
            {
                throw new CustomException(Messages.SavingFailure);
            }
        }

        /// <summary>
        /// 删除采样计划频率
        /// </summary>
        /// <param name="freq_Id">采样计划频率Id</param>
        /// <returns></returns>
        public async Task DeleteSampleFreqAsync(int freq_id)
        {
            //绑定了采样计划的计划频率不能删除
            if (await _samplePlanFreqLinkRepository.ExistsAsync(x => x.Freq_Id == freq_id))
            {
                throw new CustomException(Messages.SampleFreqBoundtoSamplePlan);
            }
            await _sampleFreqRepository.DeleteAsync(x=>x.Freq_Id== freq_id);
            int status = await _sampleFreqRepository.SaveAsync();
            if (status <= 0)
            {
                throw new CustomException(Messages.SavingFailure);
            }
        }

        /// <summary>
        /// 编辑采样计划频率
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateSampleFreqAsync(UpdatingSampleFreqInput input)
        {
            var freq = await _sampleFreqRepository.FindAsync(x => x.Freq_Id == input.Freq_Id);
            if (freq == null)
            {
                throw new CustomException(Messages.SampleFreqNotFound);
            }
            //间隔时间不能小于10秒
            if (input.Interval_Unit == 0 && input.Interval < 10)
            {
                throw new CustomException(Messages.SampleFreqIntevalCannotLessThen10S);
            }
            //采样计划频率名称不能重复
            if (await _sampleFreqRepository.ExistsAsync(x => x.Freq_Name == input.Freq_Name && x.Freq_Id != input.Freq_Id))
            {
                throw new CustomException(Messages.SampleFreqNameMustBeUnique);
            }
            freq.Freq_Name=input.Freq_Name;
            freq.Freq_Desc = input.Freq_Desc;
            freq.Enabled = input.Enabled;
            freq.Freq_Type=input.Freq_Type;
            freq.Interval = input.Interval;
            freq.Interval_Unit=input.Interval_Unit;
            freq.Offset_End=input.Offset_End;
            freq.Offset_End_Unit = input.Offset_End_Unit;
            freq.Spare1 = input.Spare1;
            freq.Spare2 = input.Spare2;
            freq.Spare3 = input.Spare3;
            freq.Spare4 = input.Spare4;
            freq.Last_Edit_At = DateTime.Now;
            var status = await _sampleFreqRepository.SaveAsync();
            if (status <= 0)
            {
                throw new CustomException(Messages.SavingFailure);
            }
        }

        /// <summary>
        /// 查询采样计划频率实体
        /// </summary>
        /// <param name="freq_id">采样计划频率Id</param>
        /// <returns></returns>
        public async Task<SampleFreqDetailResult> GetSampleFreqAsync(int freq_id)
        {
            var freq = await _sampleFreqRepository.FindAsync(x => x.Freq_Id == freq_id);
            if (freq == null)
            {
                throw new CustomException(Messages.SampleFreqNotFound);
            }
            var data = _mapper.Map<SampleFreqDetailResult>(freq);
            return data;
        }

        /// <summary>
        /// 查询采样计划频率分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedItemsData<SampleFreqResult>> GetSampleFreqsAsync(GettingSampleFreqsInput input)
        {
            Expression<Func<SampleFreq, bool>> filter = x => true;
            if (!string.IsNullOrEmpty(input.KeyWord))
            {
                filter = filter.And(x => x.Freq_Name.Contains(input.KeyWord) || x.Freq_Desc.Contains(input.KeyWord));
            }
            var freqs = await _sampleFreqRepository.Query().Where(filter).OrderByDescending(x => x.Freq_Id).ToPagedAsync(input.PagedInput);
            var data = _mapper.Map<PagedItemsData<SampleFreqResult>>(freqs);
            return data;
        }
    }
}
